package com.example.note.activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.note.R;
import com.example.note.database.ReminderEntity;
import com.example.note.service.ReminderNotificationService;
import com.example.note.viewmodel.ReminderViewModel;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.switchmaterial.SwitchMaterial;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class ReminderEditActivity extends AppCompatActivity {
    
    public static final String EXTRA_REMINDER_ID = "reminder_id";
    
    private MaterialToolbar toolbar;
    private EditText etTitle;
    private EditText etContent;
    private TextView tvReminderTime;
    private MaterialButton btnSetTime;
    private SwitchMaterial switchReminder;
    
    private ReminderViewModel reminderViewModel;
    private ReminderEntity currentReminder;
    private Calendar selectedDateTime;
    private SimpleDateFormat dateTimeFormat;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reminder_edit);
        
        initViews();
        setupToolbar();
        setupViewModel();
        setupListeners();
        loadReminderData();
        
        dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        selectedDateTime = Calendar.getInstance();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        etTitle = findViewById(R.id.etTitle);
        etContent = findViewById(R.id.etContent);
        tvReminderTime = findViewById(R.id.tvReminderTime);
        btnSetTime = findViewById(R.id.btnSetTime);
        switchReminder = findViewById(R.id.switchReminder);
    }
    
    private void setupToolbar() {
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(v -> finish());
        
        int reminderId = getIntent().getIntExtra(EXTRA_REMINDER_ID, -1);
        if (reminderId == -1) {
            toolbar.setTitle("新建备忘录");
        } else {
            toolbar.setTitle("编辑备忘录");
        }
    }
    
    private void setupViewModel() {
        reminderViewModel = new ViewModelProvider(this).get(ReminderViewModel.class);
    }
    
    private void setupListeners() {
        btnSetTime.setOnClickListener(v -> showDateTimePicker());
        
        switchReminder.setOnCheckedChangeListener((buttonView, isChecked) -> {
            btnSetTime.setEnabled(isChecked);
            tvReminderTime.setEnabled(isChecked);
            if (!isChecked) {
                tvReminderTime.setText("未设置提醒时间");
            }
        });
    }
    
    private void loadReminderData() {
        int reminderId = getIntent().getIntExtra(EXTRA_REMINDER_ID, -1);
        if (reminderId != -1) {
            reminderViewModel.getReminderById(reminderId).observe(this, reminder -> {
                if (reminder != null) {
                    currentReminder = reminder;
                    populateFields();
                }
            });
        }
    }
    
    private void populateFields() {
        if (currentReminder != null) {
            etTitle.setText(currentReminder.getTitle());
            etContent.setText(currentReminder.getContent());
            
            if (currentReminder.getReminderTime() > 0) {
                switchReminder.setChecked(true);
                selectedDateTime.setTimeInMillis(currentReminder.getReminderTime());
                tvReminderTime.setText(dateTimeFormat.format(new Date(currentReminder.getReminderTime())));
            } else {
                switchReminder.setChecked(false);
                tvReminderTime.setText("未设置提醒时间");
            }
        }
    }
    
    private void showDateTimePicker() {
        Calendar now = Calendar.getInstance();
        
        DatePickerDialog datePickerDialog = new DatePickerDialog(
            this,
            (view, year, month, dayOfMonth) -> {
                selectedDateTime.set(Calendar.YEAR, year);
                selectedDateTime.set(Calendar.MONTH, month);
                selectedDateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                
                TimePickerDialog timePickerDialog = new TimePickerDialog(
                    this,
                    (timeView, hourOfDay, minute) -> {
                        selectedDateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        selectedDateTime.set(Calendar.MINUTE, minute);
                        selectedDateTime.set(Calendar.SECOND, 0);
                        
                        tvReminderTime.setText(dateTimeFormat.format(selectedDateTime.getTime()));
                    },
                    now.get(Calendar.HOUR_OF_DAY),
                    now.get(Calendar.MINUTE),
                    true
                );
                timePickerDialog.show();
            },
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH)
        );
        
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
        datePickerDialog.show();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_reminder_edit, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        
        if (id == R.id.action_save) {
            saveReminder();
            return true;
        } else if (id == R.id.action_delete && currentReminder != null) {
            deleteReminder();
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    private void saveReminder() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        
        if (TextUtils.isEmpty(title)) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            return;
        }
        
        long reminderTime = 0;
        if (switchReminder.isChecked()) {
            reminderTime = selectedDateTime.getTimeInMillis();
            if (reminderTime <= System.currentTimeMillis()) {
                Toast.makeText(this, "提醒时间不能早于当前时间", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        
        if (currentReminder == null) {
            // 新建备忘录
            ReminderEntity newReminder = new ReminderEntity();
            newReminder.setTitle(title);
            newReminder.setContent(content);
            newReminder.setReminderTime(reminderTime);
            newReminder.setCreatedTime(System.currentTimeMillis());
            newReminder.setCompleted(false);
            
            reminderViewModel.insert(newReminder);
            
            if (reminderTime > 0) {
                ReminderNotificationService.scheduleReminder(this, newReminder);
            }
        } else {
            // 更新备忘录
            currentReminder.setTitle(title);
            currentReminder.setContent(content);
            currentReminder.setReminderTime(reminderTime);
            
            reminderViewModel.update(currentReminder);
            
            // 取消之前的提醒并设置新的提醒
            ReminderNotificationService.cancelReminder(this, currentReminder.getId());
            if (reminderTime > 0) {
                ReminderNotificationService.scheduleReminder(this, currentReminder);
            }
        }
        
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        finish();
    }
    
    private void deleteReminder() {
        if (currentReminder != null) {
            reminderViewModel.delete(currentReminder);
            ReminderNotificationService.cancelReminder(this, currentReminder.getId());
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}